package com.samehope.ar.component;

import com.alibaba.fastjson.JSON;
import com.google.common.util.concurrent.RateLimiter;
import com.samehope.ar.common.CommonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Description: 整体限流过滤器
 * @Author: ZhangLuo
 * @Email: 1946430@qq.com
 */
@Slf4j
public class RateLimiterFilter extends OncePerRequestFilter {

    private RateLimiter rateLimiter;

    public RateLimiterFilter(double count) {
        rateLimiter = RateLimiter.create(count);
    }

    /**
     * 全局限流过滤器, 全局每秒允许通过的请求数量, 在配置文件配置
     * @param httpServletRequest
     * @param httpServletResponse
     * @param filterChain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        if (rateLimiter.tryAcquire()) {
            filterChain.doFilter(httpServletRequest, httpServletResponse);
        } else {
            httpServletResponse.setHeader("Access-Control-Allow-Origin", httpServletRequest.getHeader("origin"));
            httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true");
            httpServletResponse.setCharacterEncoding("UTF-8");
            try (PrintWriter writer = httpServletResponse.getWriter()) {
                writer.write(JSON.toJSONString(CommonResult.failed("服务器忙, 请稍后再试")));
                writer.flush();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
